package com.android.qjpmc.application_module.station.fragment;

import android.graphics.Color;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.android.qjpmc.R;
import com.android.qjpmc.application_module.contract.ReportDataFragmentContract;
import com.android.qjpmc.application_module.contract.RtDataContract;
import com.android.qjpmc.application_module.home.contract.HomeContract;
import com.android.qjpmc.application_module.home.viewModel.HomeViewModel;
import com.android.qjpmc.application_module.pop.ListCheckPopupWindow;
import com.android.qjpmc.application_module.view.HisCurveLineChartView;
import com.android.qjpmc.application_module.viewModel.ReportDataFragmentViewModel;
import com.android.qjpmc.bean.GroupPointHisListBean;
import com.android.qjpmc.bean.ListCheckPopBean;
import com.android.qjpmc.bean.PointParameterBean;
import com.android.qjpmc.bean.PointTimeDataBean;
import com.android.qjpmc.bean.PwrDeviceBean;
import com.android.qjpmc.bean.ReportDataItemBean;
import com.android.qjpmc.bean.SiteStationBean;
import com.android.qjpmc.bean.StationDataBean;
import com.android.qjpmc.data_module.AnalogDataItem;
import com.android.qjpmc.data_module.PwrDataModule;
import com.android.qjpmc.databinding.FragementReportDataItemBinding;
import com.android.qjpmc.databinding.FragementRtDataItemBinding;
import com.android.qjpmc.databinding.FragmentStationPwrDiagramBinding;
import com.android.qjpmc.databinding.FragmentStationReportDataBinding;
import com.android.qjpmc.manager.IntentManager;
import com.android.qjpmc.tableview.TableViewAdapter;
import com.android.qjpmc.tableview.TableViewListener;
import com.android.qjpmc.widget.databindingadapter.BaseBindingItemPresenter;
import com.android.qjpmc.widget.databindingadapter.BaseDataBindingDecorator;
import com.android.qjpmc.widget.databindingadapter.SingleTypeBindingAdapter;
import com.android.qjpmc.widget.mvvm.factory.CreateViewModel;
import com.android.qjpmc.widget.mvvm.view.BaseMVVMFragment;
import com.android.qjpmc.widget.utils.DisplayUtils;
import com.android.qjpmc.widget.utils.TimeUtils;
import com.android.qjpmc.widget.utils.ToastUtils;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CreateViewModel(ReportDataFragmentViewModel.class)
public class ReportDataFragment extends BaseMVVMFragment<ReportDataFragmentViewModel, FragmentStationReportDataBinding> implements ReportDataFragmentContract.View, BaseBindingItemPresenter {
    int m_ready_to_query = 0;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_station_report_data;
    }

    private StationDataBean stationData;
    private String stationId;

    public void initStationData(String stationId, StationDataBean data) {
        this.stationData = data;
        this.stationId = stationId;
    }

    @Override
    public void initView() {
        mBinding.setView(this);
    }

    @Override
    public void initData() {
        mBinding.viewDevicesPoint.initDevicesListData(stationData.stationGroupList);
        mBinding.tvQueryType.setText(selectQueryType.name);

    }

    List<PointParameterBean> pointCodeList = new ArrayList<>();
    String timeUnit = "";

    @Override
    public void initEvent() {
        mBinding.viewDevicesPoint.setDevicesPointListChooseListener(resultList -> {
            pointCodeList = new ArrayList<>();
            pointCodeList = resultList;

        });
        mBinding.rgTime.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == mBinding.rbTimeDay.getId()) {
                    timeUnit = "d";
                } else if (checkedId == mBinding.rbTimeHour.getId()) {
                    timeUnit = "h";
                } else if (checkedId == mBinding.rbTimeMinute.getId()) {
                    timeUnit = "m";
                } else if (checkedId == mBinding.rbTimeSecond.getId()) {
                    timeUnit = "s";
                } else {
                    timeUnit = "";
                }
            }
        });

        mBinding.llCheckSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pointCodeList.size() <= 0) {
                    ToastUtils.showShort("请选择设备点");
                    return;
                }
                if (pointCodeList.size() > 3) {
                    ToastUtils.showShort("最多只能选择3条");
                    return;
                }
                if (TextUtils.isEmpty(m_start_time)) {
                    ToastUtils.showShort("请选择数据开始时间");
                    return;
                }
                if (TextUtils.isEmpty(m_end_time)) {
                    ToastUtils.showShort("请选择数据结束时间");
                    return;
                }

                long startTimeLong = TimeUtils.parsDataTimeLong(m_start_time, TimeUtils.DEFAULT_SDF);
                long endTimeLong = TimeUtils.parsDataTimeLong(m_end_time, TimeUtils.DEFAULT_SDF);
                if (startTimeLong >= endTimeLong) {
                    ToastUtils.showShort("开始时间不能大于结束时间");
                    return;
                }
                if (TextUtils.isEmpty(timeUnit)) {
                    ToastUtils.showShort("请选择数据时间间隔类型");
                    return;
                }
                String intervalValue = mBinding.etTimeValue.getText().toString().trim();
                if (TextUtils.isEmpty(intervalValue)) {
                    ToastUtils.showShort(mBinding.etTimeValue.getHint());
                    return;
                }

                Map<String, Object> commonMap = new HashMap();
                commonMap.put("stime", m_start_time);
                commonMap.put("etime", m_end_time);
                commonMap.put("interval", intervalValue);
                commonMap.put("timeUnit", timeUnit);
                commonMap.put("func", selectQueryType.id);
                Map<String, List<PointParameterBean>> queryPointMap = new HashMap<>();
                //组装请求数据
                for (PointParameterBean pointParameterBean : pointCodeList) {
                    String deviceTypeCode = pointParameterBean.deviceTypeCode;
                    if (queryPointMap.containsKey(deviceTypeCode)) {
                        List<PointParameterBean> list = queryPointMap.get(deviceTypeCode);
                        list.add(pointParameterBean);
                    } else {
                        List<PointParameterBean> list = new ArrayList<>();
                        list.add(pointParameterBean);
                        queryPointMap.put(deviceTypeCode, list);

                    }
                }
                //构建请求相关参数
                for (String key : queryPointMap.keySet()) {
                    List<PointParameterBean> pointParameterList = queryPointMap.get(key);
                    Map<String, Object> paramsMap = new HashMap<>();
                    Map<String, PointParameterBean> propsDataMap = new HashMap<>();
                    paramsMap.putAll(commonMap);
                    paramsMap.put("stbName", key);
                    List<String> colNameList = new ArrayList<>();
                    List<String> deviceCodeList = new ArrayList<>();
                    for (PointParameterBean pointParameterBean : pointParameterList) {
                        colNameList.add(pointParameterBean.propsCode);
                        //将每一个点的数据存下来,可以通过propsCode获取 用于构建每一个图表的title 详见returnGroupPointDataList的title组成
                        propsDataMap.put(pointParameterBean.propsCode, pointParameterBean);
                        deviceCodeList.add(pointParameterBean.deviceCode);
                    }
                    paramsMap.put("colNameList", colNameList);
                    paramsMap.put("deviceCodeList", deviceCodeList);
                    Logger.d(paramsMap);
                    mViewModel.getPointDataOfStation(stationData, paramsMap, propsDataMap);

                }
            }
        });

    }

    @Override
    public void returnGroupPointDataList(List<GroupPointHisListBean> pointDataList) {
        //   ToastUtils.showShort("数据获取到了 要刷新了");
        Logger.d("pointDataList" + pointDataList.toString());
        // TableViewModel tableViewModel = new TableViewModel();

        // Create TableView Adapter
        TableViewAdapter tableViewAdapter = new TableViewAdapter();

        mBinding.tableview.setNestedScrollingEnabled(false);
        mBinding.tableview.setAdapter(tableViewAdapter);
        mBinding.tableview.setTableViewListener(new TableViewListener(mBinding.tableview));

        // Create an instance of a Filter and pass the TableView.
        //mTableFilter = new Filter(mTableView);
        List<String> columnHeaderList = new ArrayList<>();
        List<String> rowHeaderList = new ArrayList<>();
        Map<String, List<PointTimeDataBean>> timePointListMap = new HashMap<>();

        for (int i = 0; i < pointDataList.size(); i++) {
            GroupPointHisListBean groupPointHisListBean = pointDataList.get(i);
            String title = stationData.companyName + groupPointHisListBean.deviceName + groupPointHisListBean.propsName;
            columnHeaderList.add(title);

            for (PointTimeDataBean pointTimeDataBean : groupPointHisListBean.pointValueList) {
                if (!rowHeaderList.contains(pointTimeDataBean.startTime)) {
                    rowHeaderList.add(pointTimeDataBean.startTime);
                }
                List<PointTimeDataBean> timeDataList;
                if (timePointListMap.containsKey(pointTimeDataBean.startTime)) {
                    timeDataList = timePointListMap.get(pointTimeDataBean.startTime);
                } else {
                    timeDataList = new ArrayList<>();
                }
                timeDataList.add(pointTimeDataBean);
                timePointListMap.put(pointTimeDataBean.startTime, timeDataList);
            }
        }
        //排序
        Collections.sort(rowHeaderList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (int) (TimeUtils.parsDataTimeLong(o1) - TimeUtils.parsDataTimeLong(o2));
            }
        });
        List<List<PointTimeDataBean>> cellList = new ArrayList<>();
        for (String time : rowHeaderList) {
            List<PointTimeDataBean> cellItemList = new ArrayList<>();
            for (GroupPointHisListBean groupPointHisListBean : pointDataList) {
                PointTimeDataBean cellItem = null;
                for (PointTimeDataBean pointTimeDataBean : groupPointHisListBean.pointValueList) {
                    if (pointTimeDataBean.startTime.equals(time)) {
                        cellItem = pointTimeDataBean;
                        break;
                    }
                }
                if (cellItem == null) {
                    cellItem = new PointTimeDataBean(0);
                }
                cellItemList.add(cellItem);

            }
            cellList.add(cellItemList);
        }
        // Load the dummy data to the TableView
        tableViewAdapter.setAllItems(columnHeaderList, rowHeaderList, cellList);


    }

    public void onReportData() {
        IntentManager.toReportDataActivity(mActivity);
    }

    private ListCheckPopupWindow queryTypePopupWindow;
    ListCheckPopBean selectQueryType = new ListCheckPopBean("first", "整点值", false);

    public void onCheckQueryType() {
        if (queryTypePopupWindow == null) {
            queryTypePopupWindow = new ListCheckPopupWindow((FragmentActivity) getContext());
            List<ListCheckPopBean> popListData = new ArrayList<>();
            popListData.add(new ListCheckPopBean("avg", "平均值", false));
            popListData.add(new ListCheckPopBean("max", "最大值", false));
            popListData.add(new ListCheckPopBean("min", "最小值", false));
            popListData.add(new ListCheckPopBean("first", "整点值", false));
            popListData.add(new ListCheckPopBean("dif", "区间值", false));
            queryTypePopupWindow.initListData(popListData);
            queryTypePopupWindow.setListCheckPopupWindowListener(new ListCheckPopupWindow.ListCheckPopupWindowListener() {
                @Override
                public void onPopChooseResult(List<ListCheckPopBean> popListData) {
                    for (ListCheckPopBean popListDatum : popListData) {
                        if (popListDatum.isOpen) {
                            selectQueryType = popListDatum;
                            break;
                        }
                    }

                    mBinding.tvQueryType.setText(selectQueryType.name);

                }
            });
        }
        View view = mActivity.getWindow().getDecorView();
        queryTypePopupWindow.showPopupWindowAtLocation(view);


    }

    void UpdataValuesText() {
/*
        //if ( (m_thePwrDevice != null) && (m_CurrentPwrStation != null) )
        {
            ArrayList<ReportDataItemBean> AnalogList = PwrDataModule.getInstance().GetReportDataArray();//PwrDataModule.getInstance().GetAnalogDataList(m_CurrentPwrStation.getM_ID(), m_thePwrDevice.GetID() );
            SingleTypeBindingAdapter adapter = new SingleTypeBindingAdapter(getContext(), AnalogList, R.layout.fragement_report_data_item);
            mBinding.rtDataList.setAdapter(adapter);

            adapter.setItemPresenter(this);
            mBinding.rtDataList.setNestedScrollingEnabled(false);
            mBinding.rtDataList.setLayoutManager(new LinearLayoutManager(getContext()));

            adapter.setItemDecorator(new BaseDataBindingDecorator<ReportDataItemBean, FragementReportDataItemBinding>() {

                @Override
                public void decorator(FragementReportDataItemBinding binding, int position, int viewType, ReportDataItemBean data) {
                    binding.tvName.setText(data.name);
                    binding.tvUnit.setText(data.unit);
                    binding.tvValue.setText(data.value);
                    binding.tvTime.setText(data.time);

                    binding.tvIndex.setText(Integer.toString(position + 1));
                    binding.tvName.setGravity(Gravity.CENTER);
                    binding.tvUnit.setGravity(Gravity.CENTER);
                    binding.tvValue.setGravity(Gravity.CENTER);
                    binding.tvIndex.setGravity(Gravity.CENTER);
                    binding.tvTime.setGravity(Gravity.CENTER);
                    if (position % 2 == 0) {
                        binding.tvTime.setBackgroundColor(Color.rgb(219, 238, 244));
                        binding.tvName.setBackgroundColor(Color.rgb(219, 238, 244));
                        binding.tvUnit.setBackgroundColor(Color.rgb(219, 238, 244));
                        binding.tvValue.setBackgroundColor(Color.rgb(219, 238, 244));
                        binding.tvIndex.setBackgroundColor(Color.rgb(219, 238, 244));
                    }
*/
/*
                    binding.tvIndex.setWidth(2);
                    binding.tvName.setWidth(10);
                    binding.tvValue.setWidth(10);
                    binding.tvUnit.setWidth(10);
*//*

                }
            });
        }
*/
    }

    @Override
    public void onItemClick(int position, Object itemData) {

    }

    public void onQueryReportData() {
        if (m_ready_to_query == 0) {
            Toast.makeText(this.getContext(), "请选择查询条件", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(this.getContext(), "开始查询数据", Toast.LENGTH_SHORT).show();

        UpdataValuesText();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {

            //相当于Fragment的onResume，为true时，Fragment已经可见

        } else {

            //相当于Fragment的onPause，为false时，Fragment不可见

        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {

    }

    @Override
    public void onResume() {

        super.onResume();
    }

    String m_start_time;
    String m_end_time;
    TimePickerView pvStartTime;
    TimePickerView pvEndTime;

    public void onSelectStartTime() {
        if (pvStartTime == null) {

            Calendar minDate = Calendar.getInstance();
            minDate.set(Calendar.YEAR, 1990);
            minDate.set(Calendar.MONTH, Calendar.JANUARY);
            minDate.set(Calendar.DAY_OF_MONTH, 1);
            Calendar maxDate = Calendar.getInstance();
            maxDate.setTimeInMillis(System.currentTimeMillis());

            pvStartTime = new TimePickerBuilder(this.getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_start_time = TimeUtils.DEFAULT_SDF.format(date);
                    mBinding.tvStartTime.setText(m_start_time);
                }
            }).setRangDate(minDate, maxDate).setDate(maxDate).setType(new boolean[]{true, true, true, true, true, true})
                    .build();
        }

        pvStartTime.show();
    }

    public void onSelectEndTime() {
        if (pvEndTime == null) {
            Calendar minDate = Calendar.getInstance();
            minDate.set(Calendar.YEAR, 1990);
            minDate.set(Calendar.MONTH, Calendar.JANUARY);
            minDate.set(Calendar.DAY_OF_MONTH, 1);
            Calendar maxDate = Calendar.getInstance();
            maxDate.setTimeInMillis(System.currentTimeMillis());
            pvEndTime = new TimePickerBuilder(this.getContext(), new OnTimeSelectListener() {
                @Override
                public void onTimeSelect(Date date, View v) {
                    m_end_time = TimeUtils.DEFAULT_SDF.format(date);
                    mBinding.tvEndTime.setText(m_end_time);
                }
            }).setRangDate(minDate, maxDate).setDate(maxDate)
                    .setType(new boolean[]{true, true, true, true, true, true})
                    .build();
        }
        pvEndTime.show();
    }

    public void UpdateSelectResult() {
        PwrDataModule.ReportDataQuery query = PwrDataModule.getInstance().IsNewReportQueryExist();
        if (query != null) {
         /*   mBinding.reportTitle.setText(query.station_name + "." + query.device_name);
            mBinding.beginTime.setText(query.m_start_time);
            mBinding.endTime.setText(query.m_end_time);
            m_ready_to_query = 1;*/
        }

    }

}



